<?php


namespace WenRuns\Laravel\Database;


use Encore\Admin\Grid\Exporter;

class Builder extends \Illuminate\Database\Eloquent\Builder
{
    /**
     * Chunk the results of the query.
     *
     * @param int $count
     * @param callable $callback
     * @return bool
     */
    public function chunk($count, callable $callback)
    {
        $this->enforceOrderBy();

        if (($res = $this->handlePageExport($callback)) !== null) {
            return $res;
        }

        $page = 1;

        do {
            // We'll execute the query for the given page and get the results. If there are
            // no results we can just break and return from here. When there are results
            // we will call the callback with the current chunk of these results here.
            $results = $this->forPage($page, $count)->get();

            $countResults = $results->count();

            if ($countResults == 0) {
                break;
            }

            // On each chunk result set, we will pass them to the callback and then let the
            // developer take care of everything within the callback, which allows us to
            // keep the memory low for spinning through large result sets for working.
            if ($callback($results, $page) === false) {
                return false;
            }

            unset($results);

            $page++;
        } while ($countResults == $count);

        return true;
    }


    protected function handlePageExport(callable $callback)
    {
        $scope = request(Exporter::$queryName);
        if ($scope && strpos($scope, 'page:') !== false) {
            $results = $this->get();
            list($scope, $page) = explode(':', $scope);
            if ($callback($results, $page) === false) {
                return false;
            }
            return true;
        }
        return null;
    }

}
